package nbcp.web.sys

import org.springframework.web.bind.annotation.RestController
import nbcp.base.comm.ApiResult
import nbcp.base.comm.JsonResult
import nbcp.base.comm.ListResult
import nbcp.base.comm.OpenAction
import nbcp.base.extend.AsString
import nbcp.base.utils.Md5Util
import nbcp.comm.JsonpMapping
import nbcp.db.mysql.*


@OpenAction
@RestController
@JsonpMapping("")
class Sys_Controller {
    @JsonpMapping("/user/setPassword")
    fun setPassword(userId: Int, token: String, oldPassword: String, newPassword: String): JsonResult {
        if (userId == 0) return JsonResult("缺少 userId 参数")
        if (token.isEmpty()) return JsonResult("缺少 token 参数")

        if (newPassword.length < 8) {
            return JsonResult("密码不能小于8位")
        }

        dbr.system.s_login_user.updateById(userId)
                .set { it.password to Md5Util.getBase64Md5(newPassword) }
                .where { it.password match_equal Md5Util.getBase64Md5(oldPassword)}
                .exec()

        if (dbr.affectRowCount == 0) {
            return JsonResult("更新密码失败！")
        }

        return JsonResult();
    }

    @JsonpMapping("/user/forgetPassword")
    fun forgetPassword(loginName: String): JsonResult {
        dbr.system.s_login_user.updateByLoginName(loginName)
                .set { it.forget_password to true }
                .exec()

        if (dbr.affectRowCount > 0) {
            return JsonResult();
        } else return JsonResult("找不到用户: ${loginName}")
    }

}